﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using TaobaoPick.storage;
using IE = Interop.SHDocVw;
using System.Xml;
using HAP= HtmlAgilityPack;
using System.Threading;
using TaobaoPick.taboao;
using TaobaoPick.util;
namespace TaobaoPick
{
    public class TaoLogPageHelper
    {


        public static bool processPage(Guid pageId)
        {
            MyTaobao1DataContext context = LinqAgent.getTaobaoContext();
            UrlContent uc = (from c in context.UrlContents where c.id == pageId select c).SingleOrDefault();
            if (uc == null)
            {
                //無效的頁面 id
                var tp = (from tpr in context.TaskPageRelations where tpr.pageid == pageId select tpr);
                foreach (var t in tp)
                {
                    context.TaskPageRelations.DeleteOnSubmit(t);
                }
                context.SubmitChanges();
                return false;
            }
            TaobaoQueryParser parser = new TaobaoQueryParser();
            ItemManager itm = new ItemManager();


            String content = uc.content;
            XmlDocument doc = parser.processHTML(content);
            
            try
            {
                DateTime dt=(DateTime)uc.logtime;
                int cc = itm.processItems(doc, dt);
                if (cc > 0)
                    return true;
                return false;
            }
            catch (Exception e)
            {
                //登記..
                ErrorLogs.logErrorURL(uc.url,e.Message);
            }
            return false;            
        }
        /**********************************************************************************
         * 
         * 
         * *********************************************************************************/
        public static int FixTmall()
        {
            MyTaobao1DataContext context = LinqAgent.getTaobaoContext();
            var pages = from tp in context.TaskPageRelations select tp;
            ItemManager itm = new ItemManager();
            foreach(var page in pages)
            {
                Guid id = page.pageid;
                UrlContent uc = (from urlc in context.UrlContents where urlc.id == id select urlc).FirstOrDefault();
                if (uc == null)
                    continue;
                TaobaoQueryParser parser = new TaobaoQueryParser();
                 XmlDocument doc =  parser.processHTML(uc.content);
                 itm.updateSite(doc);
            }
            return 0;
        }
        public static int processTaskPages(Guid taskId)
        {
                MyTaobao1DataContext context=LinqAgent.getTaobaoContext();
                var list = (from tp in context.TaskPageRelations where tp.taskid==taskId && tp.processed==false   select tp);
                bool hasData = false;
                foreach (var tp in list)
                {
                    hasData = true;
                    if (processPage(tp.pageid))
                    {
                        tp.processed = true;
                    }
                    else
                    {
                        tp.processed = false;
                    }
                    //processed OK
                }
                if(hasData==true)
                    context.SubmitChanges();
            
            return 0;
        }


        public static List<TaskTag> getValidTasks()
        {
            MyTaobao1DataContext context = LinqAgent.getTaobaoContext();
            List<TaskTag> r = (from t in context.TaskTags select t).ToList<TaskTag>();
            return r;
        }

        public static void preprocessImages(XmlDocument doc)
        {
            ImageSpool imspl = new ImageSpool();

            XmlNodeList list = doc.GetElementsByTagName("list-item");
            foreach (XmlNode node in list)
            {
                XmlNode img=node.SelectSingleNode("img");
                if(img==null)
                    continue;
                //---->有img guid
                try
                {
                    Guid newid = imspl.preloadItemFromCache(img.InnerText);
                    XmlNode tid = doc.CreateElement("thumbId");
                    tid.InnerText = newid.ToString();
                    node.AppendChild(tid);
                }
                catch (Exception e)
                {
                    
                }
            }
        }

        
        public static int performFakeOpen(XmlDocument doc, int count)
        {
            List<String> ts=ramdonPickLink(doc, 3);
            System.Random num = new Random();
            foreach (String url in ts)
            {
                int c = num.Next(5, 15) * 1000;
                Thread.Sleep(c);
                HAP.HtmlDocument hapdoc = LoadOnePage(url);                
            }
            int r=ts.Count;
            ts.Clear();
            return r;
        }


        protected static HtmlAgilityPack.HtmlWeb web = new HAP.HtmlWeb();
        public static List<String> ramdonPickLink(XmlDocument doc, int count)
        {
            List<String> result = new List<string>();

            XmlNodeList list = doc.GetElementsByTagName("list-item");
            if (list.Count <=count+1)
                return result;
            System.Random num = new Random();
            int t=num.Next(0,count-1);

            for(int i=0;i<t;i++)
            {
                int se = num.Next(1, list.Count - 1);
                XmlNode node = list.Item(se);
                XmlNode logUrl = node.SelectSingleNode("logUrl");
                XmlNode itemUrl = node.SelectSingleNode("itemUrl");
                if (itemUrl != null)
                {
                    result.Add(itemUrl.InnerText);
                }
                else if(logUrl!=null)
                {
                    result.Add(logUrl.InnerText);
                }
            }
            
            return result;
        }

        public static   HAP.HtmlDocument LoadOnePage(String url)
        {
            HAP.HtmlDocument doc = web.Load(url);
            Uri uri=web.ResponseUri;
            System.Diagnostics.Trace.WriteLine(url);
            System.Diagnostics.Trace.WriteLine(uri.AbsolutePath); 
            return doc;
        }
        /******************************************
         * 
         * 
         * *****************************************/
        public static Guid createTaskTag(String tagName)
        {
            MyTaobao1DataContext context = LinqAgent.getTaobaoContext();
            TaskTag tt = new TaskTag();
            tt.taskId = NewGUID.create("task");
            tt.tagName = tagName;
            tt.createdAt = DateTime.Now;
            context.TaskTags.InsertOnSubmit(tt);
            context.SubmitChanges();
            return tt.taskId;
        }
        public static Guid  storePage( Guid taskId, String url,String content)
        {
            MyTaobao1DataContext context = LinqAgent.getTaobaoContext();
            if((taskId==null)||(Guid.Empty.Equals(taskId)))
            {
                taskId=createTaskTag("ungrouped");
            }
            //產生一個 taskPageRelations
            UrlContent uc = new UrlContent();
            uc.id = NewGUID.create("html");
            uc.logtime=DateTime.Now;
            uc.content=content;
            uc.url=url;
            context.UrlContents.InsertOnSubmit(uc);

            TaskPageRelation tpr = new TaskPageRelation();
            tpr.pageid = uc.id;
            tpr.taskid = taskId;
            tpr.processed = false;
            context.TaskPageRelations.InsertOnSubmit(tpr);
            context.SubmitChanges();
            return taskId;
        }
        public static bool hasValidSale(XmlDocument doc, int thr)
        {
            if (doc == null)
                return false;
            XmlNodeList list = doc.GetElementsByTagName("list-item");
            foreach (XmlNode node in list)
            {
                XmlNode recentSale = node.SelectSingleNode("recentSale");
                if (recentSale == null)
                    continue;
                int s = 0;
                int.TryParse(recentSale.InnerText, out s);
                if (s > thr)
                    return true;
            }
            return false;
        }

        public static bool hasValidSale(XmlDocument doc)
        {
            return hasValidSale(doc, 0);
        }
        public static String getNextPageURL(XmlDocument doc)
        {
            if (doc == null)
                return null;
            String nextURL = null;
            XmlNodeList nexts = doc.DocumentElement.GetElementsByTagName("page-next");
            if (nexts.Count> 0)
            {
                foreach (XmlNode node in nexts)
                {
                    nextURL = node.InnerText;
                    break;
                }
            }
            return nextURL;
        }
    }
}
